package com.pai4j.pgc.service.behavior;
import com.pai4j.common.exception.BusinessException;
import com.pai4j.common.util.SpringContextUtil;
import com.pai4j.pgc.dao.community.IResourceBehaviorDAO;
import com.pai4j.pgc.entity.community.ResourceBehaviorEntity;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

/**
 * 资源行为服务 - 写 (双向：包含取消行为)
 */
public class ResourceTwoWayBehaviorService extends AbstractResourceBehaviorService {

    @Override
    public boolean behaviorResource(String userId, Long resourceIndex, String resourceType, String behaviorType) {
        IResourceBehaviorDAO resourceBehaviorDAO = SpringContextUtil.getBean(IResourceBehaviorDAO.class);
        List<ResourceBehaviorEntity> behaviorEntityList =
                resourceBehaviorDAO.findAllByUserIdAndResourceIndexAndResourceTypeAndBehaviorType(
                        userId, resourceIndex, resourceType, behaviorType);
        ResourceBehaviorEntity behaviorEntity;
        if (CollectionUtils.isNotEmpty(behaviorEntityList)) {
            behaviorEntity = behaviorEntityList.get(0);
            if (behaviorEntity.getStatus()) {
                return true;
            }
        } else {
            behaviorEntity = new ResourceBehaviorEntity();
            behaviorEntity.setUserId(userId);
            behaviorEntity.setResourceIndex(resourceIndex);
            behaviorEntity.setResourceType(resourceType);
            behaviorEntity.setBehaviorType(behaviorType);
        }
        behaviorEntity.setStatus(Boolean.TRUE);
        resourceBehaviorDAO.save(behaviorEntity);
        return true;
    }

    @Override
    public boolean cancelBehaviorResource(String userId, Long resourceIndex, String resourceType, String behaviorType) {
        IResourceBehaviorDAO resourceBehaviorDAO = SpringContextUtil.getBean(IResourceBehaviorDAO.class);
        List<ResourceBehaviorEntity> behaviorEntityList =
                resourceBehaviorDAO.findAllByUserIdAndResourceIndexAndResourceTypeAndBehaviorType(
                        userId, resourceIndex, resourceType, behaviorType);
        ResourceBehaviorEntity behaviorEntity;
        if (CollectionUtils.isNotEmpty(behaviorEntityList)) {
            behaviorEntity = behaviorEntityList.get(0);
            if (behaviorEntity.getStatus()) {
                behaviorEntity.setStatus(false);
            }
        } else {
            throw new BusinessException("不能重复操作");
        }
        resourceBehaviorDAO.save(behaviorEntity);
        return true;
    }
}
